package side_panel

import (
	"strings"

	"file_explorer/common/consts"
	"file_explorer/common/log"
	"file_explorer/common/util"
	"file_explorer/service/third_program"
	"file_explorer/view/components/side_panel/dir_tree"
	"file_explorer/view/components/side_panel/favorites"
	"file_explorer/view/components/side_panel/op_list"
	"file_explorer/view/packed_widgets"
	"file_explorer/view/store"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"github.com/spf13/cast"
)

type SidePanel struct {
	*container.Scroll
	DirTree   *packed_widgets.Tree
	OpList    *op_list.OpList
	Favorites *favorites.FavoritesList

	gCtx *store.GlobalContext
}

func newSidePanelMenu(gCtx *store.GlobalContext) *packed_widgets.MenuButton {
	menu := packed_widgets.NewMenuButton("", theme.MoreHorizontalIcon())
	menu.AddItem("设置", nil, func(interface{}) {
		log.Info("打开设置")
		gCtx.AddTab(store.NewSettingTabContext(gCtx))
	})
	menu.AddItem("任务列表", nil, func(interface{}) {
		log.Info("打开任务列表")
		gCtx.AddTab(store.NewTaskListTabContext(gCtx))
	})
	menu.AddItem("日志", nil, func(interface{}) {
		logWindow := packed_widgets.NewWindow("日志")

		panel := newLogPanel(gCtx)

		log.UpdateLogger(panel)

		logWindow.SetContent(container.NewBorder(
			panel.GetClearButton(), nil, nil, nil, panel.GetEntry(),
		))
		logWindow.Resize(fyne.NewSize(600, 400))
		logWindow.Show()
		logWindow.SetOnClosed(func() {
			log.UpdateLogger(nil)
		})
	})

	return menu
}

func newSearchBox(gCtx *store.GlobalContext) *widget.Entry {
	searchBox := widget.NewEntry()
	searchBox.PlaceHolder = "Path"
	searchBox.OnSubmitted = func(text string) {
		text = strings.TrimSpace(text)

		pathPrefix := "path:"
		if strings.HasPrefix(text, pathPrefix) {
			text = strings.TrimSpace(text[len(pathPrefix):])
			gCtx.AddTab(store.NewFileTabContext(gCtx, text))
			return
		}

		// 按关键词搜索
		fileInfos, err := third_program.GetCaller().SearchByEverything(text)
		if err != nil {
			packed_widgets.NotifyError("搜索失败，错误：%s", err.Error())
			return
		}
		log.Info("搜索关键词：%s，结果：%d项", text, len(fileInfos))
		gCtx.AddTab(store.NewSearchResTabContext(gCtx, text, fileInfos))
	}

	return searchBox
}

func NewSidePanel(gCtx *store.GlobalContext) *SidePanel {
	sidePanel := &SidePanel{
		DirTree:   dir_tree.NewDirTree(gCtx),
		Favorites: favorites.NewFavorites(gCtx),
		OpList:    op_list.NewOpList(gCtx.OpListContext),
		gCtx:      gCtx,
	}

	dirTreeTab := container.NewTabItem("目录树", sidePanel.DirTree.Tree) //不加.Tree时点击事件响应慢
	favoritesTab := container.NewTabItem("收藏夹", sidePanel.Favorites.Tree.Tree)
	opListTab := container.NewTabItem("操作列表", sidePanel.OpList.Container)
	sidePanelTabs := container.NewAppTabs(
		dirTreeTab,
		favoritesTab,
		opListTab,
	)

	// 检查收藏夹目录是否都存在
	sidePanelTabs.OnSelected = func(item *container.TabItem) {
		if gCtx.GetGlobalConf().FavoritesNotExist == consts.FavoritesNotExistIgnore ||
			item != favoritesTab || len(gCtx.GetGlobalConf().Favorites) == 0 {
			return
		}

		invalidFavorites := make([]string, 0)
		for _, favoriteItem := range gCtx.GetGlobalConf().Favorites {
			if !util.PathExists(favoriteItem.Path) {
				invalidFavorites = append(invalidFavorites, favoriteItem.Name)
			}
		}

		log.Info("收藏夹失效目录数：%d", len(invalidFavorites))

		if len(invalidFavorites) == 0 {
			return
		}

		if gCtx.GetGlobalConf().FavoritesNotExist == consts.FavoritesNotExistDelete {
			err := gCtx.ClearInvalidFavorites()
			if err != nil {
				packed_widgets.NotifyError("清除收藏夹无效目录失败，错误：%s", err.Error())
				return
			}
			return
		}

		info := "以下收藏目录已失效: \n" + cast.ToString(invalidFavorites)
		dialog.ShowConfirm("确认删除", info,
			func(confirm bool) {
				if !confirm {
					return
				}
				err := gCtx.ClearInvalidFavorites()
				if err != nil {
					packed_widgets.NotifyError("清除收藏夹无效目录失败，错误：%s", err.Error())
					return
				}
			},
			packed_widgets.GetAppWindow())

	}

	sidePanel.Scroll = container.NewHScroll(
		container.NewBorder(
			newSearchBox(gCtx),
			newSidePanelMenu(gCtx),
			nil,
			nil,
			sidePanelTabs,
		),
	)

	return sidePanel
}
